package com.atguigu.myjuc.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class SaleTicketsDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(()->{
            for (int i = 0; i < 51; i++) ticket.saleTicket();
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 51; i++) ticket.saleTicket();
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 51; i++) ticket.saleTicket();
        },"C").start();

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    ticket.saleTicket();
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    ticket.saleTicket();
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    ticket.saleTicket();
                }
            }
        },"C").start();*/

    }
}

class Ticket{
    int number = 50;

    /*public synchronized void saleTicket(){
        if(number > 0){
            System.out.println("线程" + Thread.currentThread().getName() + " 卖出了第: " + number-- + "张票还剩" + number + "张");
        }
    }*/

    /*public void saleTicket(){
        synchronized (Object.class) {
            if (number > 0) {
                System.out.println("线程" + Thread.currentThread().getName() + " 卖出了第: " + number-- + "张票还剩" + number + "张");
            }
        }
    }*/

    private final Lock lock = new ReentrantLock();
    private final Lock lock1 = new ReentrantLock(true);

    public void saleTicket(){
        lock.lock();
        lock1.lock();
        try {
            if(number > 0){
                System.out.println("线程" + Thread.currentThread().getName() + " 卖出了第: " + number-- + "张票还剩" + number + "张");
            }
        } finally {
            lock.unlock();
        }
    }
}
